package resource

import (
	"project-info/src/handle/common"
	"project-info/src/handle/response"
	"project-info/src/model"
	"gorm.io/gorm"

	"project-info/src/lib")

type ServerReq struct {
	Query string `json:"query"`
	common.PageRequest
}

func AddServer(c *lib.GinContext) error {
	// 1.解析参数
	var server *model.Server
	if err := c.Bind(&server); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}
	// 2.检验server是否存在
	var count int64
	db := model.DB().Model(&model.Server{}).Where("ip = ?", server.Ip)
	if err := db.Count(&count).Error; err != nil {
		return response.JsonFail(c, "查询数据库失败")
	}

	if count > 0 && server.Id == 0 {
		return response.JsonFail(c, "服务器已存在")
	}

	// 3.保存数据
	if server.Id == 0 {
		model.DB().Create(&server)
	} else {
		model.DB().Save(&server)
	}
	return response.JsonOk(c, server, "保存成功")
}

func PageServer(c *lib.GinContext) error {
	// 1.解析参数
	var req ServerReq
	if err := c.Bind(&req); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}
	// 2.查询数据
	var servers []*model.Server
	var total int64
	db := model.DB().Model(&model.Server{})
	if req.Query != "" {
		db = db.Where("ip like ?", "%"+req.Query+"%")
	}
	if err := db.Count(&total).Order("id desc").Offset((req.Page - 1) * req.Size).Limit(req.Size).Find(&servers).Error; err != nil && err != gorm.ErrRecordNotFound {
		return response.JsonFail(c, "查询数据库失败")
	}

	return response.JsonOk(c, map[string]interface{}{"records": servers, "total": total}, "查询成功")
}

func DeleteServer(c *lib.GinContext) error {
	// 1.解析参数
	var server *model.Server
	if err := c.Bind(&server); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}
	// 2.删除数据
	if err := model.DB().Delete(&server).Error; err != nil {
		return response.JsonFail(c, "删除失败")
	}
	return response.JsonOk(c, nil, "删除成功")
}

func BindServer(c *lib.GinContext) error {
	// 1.解析参数
	var bindReq *BindReq
	if err := c.Bind(&bindReq); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}
	// 从bindReq中获取resourceUser和resourceRole
	var resourceUser []*model.ResourceUser
	var resourceRole []*model.ResourceRole
	for _, userId := range bindReq.UserIds {
		resourceUser = append(resourceUser, &model.ResourceUser{UserId: userId, ResourceId: bindReq.ResourceId})
	}
	for _, roleId := range bindReq.RoleIds {
		resourceRole = append(resourceRole, &model.ResourceRole{RoleId: roleId, ResourceId: bindReq.ResourceId})
	}

	err := model.DB().Transaction(func(tx *gorm.DB) error {
		// 2.删除数据
		if err := tx.Where("resource_id = ?", bindReq.ResourceId).Delete(&model.ResourceUser{}).Error; err != nil {
			return err
		}

		if err := tx.Where("resource_id = ?", bindReq.ResourceId).Delete(&model.ResourceRole{}).Error; err != nil {
			return err
		}

		// 3.保存数据
		if err := tx.Create(&resourceUser).Error; err != nil {
			return err
		}

		if err := tx.Create(&resourceRole).Error; err != nil {
			return err
		}

		return nil
	})
	if err != nil {
		return response.JsonFail(c, "绑定失败")
	}
	return response.JsonOk(c, nil, "绑定成功")
}

func ListServer(c *lib.GinContext) error {
	// 1.查询数据
	var servers []*model.Server
	if err := model.DB().Find(&servers).Error; err != nil {
		return response.JsonFail(c, "查询数据库失败")
	}
	var options []*common.OptionRes
	for _, server := range servers {
		options = append(options, &common.OptionRes{Label: server.Ip, Value: server.Ip})
	}
	return response.JsonOk(c, options, "查询成功")
}
